package com.itheima.service.db.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.Freeze;
import com.itheima.domain.db.UserInfo;
import com.itheima.mapper.FreezeMapper;
import com.itheima.mapper.UserInfoMapper;
import com.itheima.service.db.FreezeService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@DubboService
public class freezeServiceImpl implements FreezeService {

    @Autowired
    private FreezeMapper freezeMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;


    //查询冻结用户信息
    @Override
    public Freeze findByFreeze(Long userId) {
        QueryWrapper<Freeze> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        return freezeMapper.selectOne(qw);
    }

    //冻结用户
    @Override
    public void freezeByUser(Freeze freeze) {
        //在冻结表新增或修改
        Freeze byFreeze = findByFreeze(freeze.getUserId());

        if(byFreeze==null){//之前 没有 被冻结过
            freeze.setUserStatus(2);
            freezeMapper.insert(freeze);
        }else {//之前 有 被冻结过
            byFreeze.setFreeze(freeze);
            byFreeze.setUserStatus(2);
            freezeMapper.updateById(byFreeze);
        }


        //在userInfo表设置状态
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.eq("id",freeze.getUserId());
        UserInfo user = userInfoMapper.selectOne(qw);
        user.setUserStatus("2");
        userInfoMapper.updateById(user);
    }

    //手动解冻用户
    @Override
    public void unFreezeByUser(Long userId, String reasonsForThawing) {
        //查询被解冻的用户
        Freeze freeze = findByFreeze(userId);
        //修改被解冻的用户
        freeze.setUserStatus(1);//1：正常，2：冻结状态
        freeze.setReasonsForThawing(reasonsForThawing);//解冻备注
        freeze.setFinishTime(new Date());//解冻时间
        freezeMapper.updateById(freeze);

        //在userInfo表设置状态
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.eq("id",freeze.getUserId());
        UserInfo user = userInfoMapper.selectOne(qw);
        user.setUserStatus("1");
        userInfoMapper.updateById(user);
    }
    //自动解冻用户
    @Override
    public void unFreezeByUserAuto(Long userId) {
        //查询被解冻的用户
        Freeze freeze = findByFreeze(userId);
        //修改被解冻的用户
        freeze.setUserStatus(1);//1：正常，2：冻结状态
        freeze.setReasonsForThawing("自动解冻");//解冻备注
        freezeMapper.updateById(freeze);

        //在userInfo表设置状态
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.eq("id",freeze.getUserId());
        UserInfo user = userInfoMapper.selectOne(qw);
        user.setUserStatus("1");
        userInfoMapper.updateById(user);
    }


}
